<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios取消请求</title>
    <script src="axios.js"></script>
</head>

<body>
<button>发送请求</button>
<button>取消请求</button>
<script>
    const btn = document.querySelectorAll('button')
    let cancel = null
    btn[0].addEventListener('click', function () {
        //防止重复请求
        if (cancel) cancel()
        axios({

            method: 'GET',
            url: 'http://localhost:3000/posts',
            //1.添加配置属性对象:取消标识
            cancelToken: new axios.CancelToken(function (c) {
                //将c赋值给cancel
                cancel = c
            })
        }).then(response => {
            console.log(response)
            //处理完了之后置为null,下一次请求进来就不会认为事重复请求了
            cancel = null
        })
    })

    //取消按钮点击事件调用取消函数即可
    btn[1].addEventListener('click', function () {
        //取消请求
        cancel()
    })
</script>
</body>
</html>